package com.yl.zqy.config;

import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.jwt.StpLogicJwtForSimple;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpLogic;
import cn.dev33.satoken.stp.StpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.Arrays;
import java.util.List;

/**
 * @Description Sa-Token 路由拦截器
 * @Author liang.yu
 * @Date 2024/3/24 10:38
 */
@Configuration
@Slf4j
public class SaTokenConfigure implements WebMvcConfigurer {
    @Value("${zqy.anon.url}")
    private String anonUrl;

    // Sa-Token 整合 jwt (Simple 简单模式)
    @Bean
    public StpLogic getStpLogicJwt() {
        return new StpLogicJwtForSimple();
    }

    // 注册拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        // 注册 Sa-Token 拦截器，定义详细认证规则
        registry.addInterceptor(new SaInterceptor(handler -> {
            // 指定一条 match 规则
            SaRouter.match("/**")
                    .notMatch(excludePaths())
                    .check(r -> StpUtil.checkLogin());
        }).isAnnotation(false)).addPathPatterns("/**");
    }

    // 动态获取哪些 path 可以忽略鉴权
    public List<String> excludePaths() {
        String[] anonUrlList = anonUrl.split(";");
        return Arrays.asList(anonUrlList);
    }
}
